package cn.chengpengper.shortlink.component;

import cn.chengpengper.shortlink.config.SmsConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author huchengpeng
 * @version v1.0.0
 * @date 2023/8/20 16:38
 * @description SMS 短袖组件
 */
@Slf4j
@Component
public class SmsComponent {

    private final RestTemplate restTemplate;

    private final SmsConfig smsConfig;

    public SmsComponent(RestTemplate restTemplate, SmsConfig smsConfig) {
        this.restTemplate = restTemplate;
        this.smsConfig = smsConfig;
    }

    /**
     * 发送短信验证码
     *
     * @param to         目标手机号
     * @param templateId 短信模版ID
     * @param value      验证码值
     */
    @Async("smsTaskExecutor")
    public void send(String to, String templateId, String value) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "APPCODE " + smsConfig.getAppCode());
        headers.add("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        MultiValueMap<String, String> bodys = new LinkedMultiValueMap<>(8);
        bodys.add("content", "code:" + value);
        bodys.add("template_id", templateId);
        bodys.add("phone_number", to);

        HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(bodys, headers);

        ResponseEntity<String> response = restTemplate.exchange(smsConfig.getUrl(), HttpMethod.POST, entity, String.class);
        log.info("SmsComponent | send | url={},body={}", smsConfig.getUrl(), response.getBody());
        if (response.getStatusCode().is2xxSuccessful()) {
            log.info("SmsComponent | send | TO {} 发送短信验证码成功", to);
        } else {
            log.error("SmsComponent | send | TO {} 发送短信验证码失败", to);
        }
    }
}
